package com.itheima;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@SpringBootApplication
@EnableAsync // 开启异步线程支持 @Async异步调用
@MapperScan(basePackages = "com.itheima.sync.mapper")
@EnableScheduling
public class SyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SyncApplication.class,args);
    }

    //配置线程池
    @Bean(name = "taskExecutor")
    public TaskExecutor taskExecutor() {
        // 使用线程池时，必须得自己new出来，不是调用Executors.静态方法
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        // 计算型(算法) cpu核心数+1
        // io型(磁盘|网络操作) 2倍cpu核心数
        executor.setCorePoolSize(20);
        // 设置最大线程数
        executor.setMaxPoolSize(40); // 防止创建无限多的线程, oom
        // 设置队列容量
        executor.setQueueCapacity(200); // 高并发时，大理的阻塞线程，占满队列，导致oom
        // 设置非核心线程(空闲时)的存活时长（秒）
        executor.setKeepAliveSeconds(60); //
        // 设置默认线程名称,为了区分是系统还是业务的
        executor.setThreadNamePrefix("taskExecutor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);

        executor.initialize();
        return executor;
    }
}
